const router = require('koa-router')()
const fs = require('fs')
const path = require('path')

router.post('/', async (ctx) => {
  // image 是前端传过来的name值
  // console.log(ctx.request)

  try {
    const file = ctx.request.files.image // 获取上传文件
    console.log(file)
    const reader = fs.createReadStream(file.path)
    const filePath = path.join(__dirname, '../public/uploads') + `/${file.name}`
    // 创建可写流
    const upStream = fs.createWriteStream(filePath)
    // 可读流通过管道写入可写流
    reader.pipe(upStream)
    const webpath = filePath.split('public')[1]
    ctx.body = {
      code: 200,
      msg: '上传成功',
      webpath
    }
  } catch (err) {
    console.log(err)
    ctx.body = {
      code: 500,
      msg: '上传失败'
    }
  }
})

module.exports = router
